package fudan.se.project.service.infrastructure.base;

import fudan.se.project.service.infrastructure.entity.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author X Yang
 */
@Service
public class UserAuthenticationService implements UserDetailsService {

    private UserService userService;

    @Autowired
    public UserAuthenticationService(UserService userService) {
        this.userService = userService;
    }


    /**
     * Loads the user with appointed username.
     *
     * @return a User(UserDetails impl) not null.
     * @throws UsernameNotFoundException if no such user exists with the username.
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        if (userService.isUserExistent(username))
            return userService.findByUsername(username);
        else
            throw new UsernameNotFoundException("Not existent, User: " + username);
    }


}
